Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
Vue 3: What's the proper way of handling event listeners like "visibilitychange" and "offline"?

Note A: I'm not talking about event listeners on elements, like @click

Note B: I've been looking "all over" for this but couldn't find it anywhere. Feel free to slap my face if the answer is out there.

Note C: I'm a beginner with Vue trying to learn stuff

I guess I could put those kind of event listeners within main.js, but that just seems a bit off? Also how would I call functions declared within App.vue from main.js?

I'm guessing there's a better and more proper way to handle this within App.vue and the life cycle?

Any help would be greatly appreciated!

Here are two vanilla JS code examples, one with window and one with document:

window.addEventListener('offline', function() {
  alert('You seem to be offline!');
});

document.addEventListener('visibilitychange', function() {
  if (document.visibilityState === 'visible') {
    alert('Hello again!');
  }
});

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can set the event listener in the created or mounted hook in your SFC like this:

<script>
export default {
  created () {
    document.addEventListener('visibilitychange', this.handleVisibility, false)
  },
  methods: {
    handleVisibility (e) {
      if (document.visibilityState === 'hidden') {
        // do what you like
      } else {
        // again do as you like
      }
    }
  }
};
</script>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!